#   This file is part of Metriflot.
#
#    Metriflot is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    Metriflot is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with Metriflot.  If not, see <http://www.gnu.org/licenses/>.
#
#    Copyright 2011 David Irvine
# 
# Create your views here.
from django.template import Context, loader

import datetime
from django.http import HttpResponse, HttpResponseRedirect,HttpResponseBadRequest

import json
from SimpleStat.models import Metric, Report, Graph


def getSeriesData(series=None):
	data=[]
	metrics=Metric.objects.all().filter(series__exact=series).order_by('ts')
	lasttime=0
	if len(metrics)>0:
		lasttime=metrics[0].chartArray()[0]

	for m in metrics:
		# There is at least one entry 
		newRecord=m.chartArray()
		import logging
		if newRecord[0]>(lasttime+2*60*1000):
			logging.error("Foo")
			data.append([(lasttime+2*60*1000),None])
		data.append(newRecord)
		lasttime=newRecord[0]

	return data


from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def uploadMetric(request):
	if not request.method == 'POST':
		return HttpResponseBadRequest("No Post data")

	arr=json.loads(request.raw_post_data)
	for data in arr: 
		m=Metric()
		m.system=data['system']
		m.series=data['series']
		m.value=data['value']
		m.ts=datetime.datetime.fromtimestamp(data['ts'])
		m.save()
	return HttpResponse("OK",mimetype="text/plain")


from django.shortcuts import get_object_or_404

def getGraphData(request, graphId=None):
	g=get_object_or_404(Graph, pk=graphId)

	graph={
		'id':graphId,
		'placeholder':'#graph_id_'+str(graphId),
		'series':[],
		'options':{
			'xaxis':{
				'mode':'time',
				},
			},
	}
	for s in g.series.all():
		series={
			'name':s.name,
			'label':s.name,
			}
		for opt in s.options.all():
			value=opt.value
			
			try:
				value=json.loads(value)
			except:
				pass
			series[opt.name]=value
		graph['series'].append(series)


	
	for o in g.options.all():
		graph['options'][o.name]=o.value

	for s in graph['series']:
		s['data']=getSeriesData(series=s['name'])
		

	return HttpResponse(json.dumps(graph,sort_keys=True, indent=4), mimetype="text/plain")


def getReport(request, reportId=None):
	report=get_object_or_404(Report,pk=reportId)

	graphs=report.graphs.all()
	t = loader.get_template('reports/index.html')
	c = Context({
		'graphs': graphs,
	})
	return HttpResponse(t.render(c))


